package com.example.demo.kafka.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:xuecx
 * @descript:<p> </p>
 * @date:2019/6/3
 */
//@Configuration
//@EnableKafka
public class KafkaProducerConfig {
    //@Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<String, String>(createKafkaFactory());
    }

    public Map<String, Object> setProperties() {
        Map map = new HashMap();
        map.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        //重试次数
        map.put(ProducerConfig.RETRIES_CONFIG, 3);
        map.put(ProducerConfig.BATCH_SIZE_CONFIG, 10240);
        // //往kafka服务器提交消息间隔时间，0则立即提交不等待
        map.put(ProducerConfig.LINGER_MS_CONFIG, 0);
        map.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 10240);
        map.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 3000);
        map.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        map.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return map;
    }

    public DefaultKafkaProducerFactory createKafkaFactory() {
        return new DefaultKafkaProducerFactory(setProperties());
    }
}
